﻿using FineUI;
using SysManage.BLL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZHDJ.Core;
using ZHDJ.Core.Caching;
using ZHDJ.Core.Log;
using ZHDJ.Core.Util;
using ZHDJ.Data;
using ZHDJ.Data.Models;
using ZHDJ.Data.Models.Org;
using ZHDJ.WebPage;

namespace SysManage.Module.VideoProbe
{
    public partial class VideoProbeList : PageBase
    {
        #region ViewPower

        /// <summary>
        /// 本页面的浏览权限，空字符串表示本页面不受权限控制
        /// </summary>
        public override string ViewPower
        {
            get
            {
                //return "VideoProbeView";
                return "";
            }
        }
        #endregion

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindTree();
                LoadData();
            }
        }

        private void LoadData()
        {
            // 权限检查
            //CheckPowerWithButton("PartyOrgBranchAdd", btnNew);
            //CheckPowerWithButton("PartyOrgBranchDelete", btnDeleteSelected);

            btnNew.OnClientClick = Window1.GetShowReference("VideoProbeEdit.aspx", "新增");
            ResolveDeleteButtonForGrid(btnDeleteSelected, Grid2, "确定要从删除选中的{0}项记录吗？");

            // 默认选中第一个部门
            //Grid1.SelectedRowIndex = 0;

            // 每页记录数
            Grid2.PageSize = ConfigHelper.PageSize;
            ddlGridPageSize.SelectedValue = ConfigHelper.PageSize.ToString();

            BindGrid();
        }

        private void BindTree()
        {
            TreeControlBusiness tree = new TreeControlBusiness("BranchID", "ParentBranchID", "BranchName", true, CacheKeys.Cache_Branch_Tree);
            tree.EnableClickEvent = true;
            tree.BindTreeBranch(TreeBranch);
            if (!string.IsNullOrEmpty(BranchID))
            {
                var n = TreeBranch.FindNode(BranchID);

                TreeBranch.Nodes.Clear();
                if (n != null)
                    TreeBranch.Nodes.Add(n);
            }
            if (TreeBranch.Nodes.Count > 0)
            {
                //展开第一层
                TreeBranch.Nodes[0].Expanded = true;
            }
            if (!IsSystemAdmin)
            {
                btnDeleteSelected.Hidden = true;
                btnNew.Hidden = true;
            }
        }

        private void BindGrid()
        {
            string parentBranchID = hdParentBranchID.Text;

            if (parentBranchID == "")
            {
                Grid2.RecordCount = 1;

                Grid2.DataSource = partyvideoprobe.GetGridData(Grid2.PageIndex, Grid2.PageSize, "", this.txtSearchName.Text.Trim());
                Grid2.DataBind();
            }
            else
            {
                var ds = partyvideoprobe.GetGridData(Grid2.PageIndex, Grid2.PageSize, parentBranchID, this.txtSearchName.Text.Trim());
                // 在查询添加之后，排序和分页之前获取总记录数
                Grid2.RecordCount = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
                Grid2.DataSource = ds.Tables[0];
                Grid2.DataBind();
            }
        }
        #endregion

        #region 事件

        protected void ddlGridPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid2.PageSize = Convert.ToInt32(ddlGridPageSize.SelectedValue);
            BindGrid();
        }
        #endregion

        #region Grid1 Events

        protected void Grid1_RowClick(object sender, FineUI.GridRowClickEventArgs e)
        {
            BindGrid();
        }

        #endregion

        #region Grid2 Events
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void TreeBranch_NodeCommand(object sender, TreeCommandEventArgs e)
        {
            hdParentBranchID.Text = e.Node.NodeID;
            BindGrid();
        }

        protected void Grid2_Sort(object sender, GridSortEventArgs e)
        {
            Grid2.SortDirection = e.SortDirection;
            Grid2.SortField = e.SortField;
            BindGrid();
        }

        protected void Grid2_PageIndexChange(object sender, GridPageEventArgs e)
        {
            Grid2.PageIndex = e.NewPageIndex;
            BindGrid();
        }

        protected void btnDeleteSelected_Click(object sender, EventArgs e)
        {
            // 在操作之前进行权限检查
            //if (!CheckPower("PartyOrgBranchDelete"))
            //{
            //    CheckPowerFailWithAlert();
            //    return;
            //}

            // 从每个选中的行中获取ID（在Grid1中定义的DataKeyNames）
            List<string> ids = GetSelectedDataKeyIDs(Grid2);

            // 执行数据库操作
            DB.partyvideoprobes.Where(u => ids.Contains(u.ID)).ToList().ForEach(u => DB.partyvideoprobes.Remove(u));
            DB.SaveChanges();
            BindGrid();

            MemoryCacheManager CacheManager = new MemoryCacheManager();
            CacheManager.Remove(CacheKeys.Cache_Branch_Camera_Tree_Navigation);
            CacheManager.Remove(CacheKeys.Cache_Camera_Branch_All);
        }

        protected void Grid2_RowCommand(object sender, GridCommandEventArgs e)
        {
            string IDs = GetSelectedDataKeyID(Grid2);

            if (e.CommandName == "Delete")
            {
                // 在操作之前进行权限检查
                //if (!CheckPower("PartyEduHonourDelete"))
                //{
                //    CheckPowerFailWithAlert();
                //    return;
                //}

                var del = DB.partyvideoprobes.FirstOrDefault(t => t.ID == IDs);
                DB.partyvideoprobes.Remove(del);
                DB.SaveChanges();
                BindGrid();

                MemoryCacheManager CacheManager = new MemoryCacheManager();
                CacheManager.Remove(CacheKeys.Cache_Branch_Camera_Tree_Navigation);
                CacheManager.Remove(CacheKeys.Cache_Camera_Branch_All);
            }
        }

        protected void Window1_Close(object sender, EventArgs e)
        {
            BindGrid();
        }

        //protected void btnNew_Click(object sender, EventArgs e)
        //{
        //    string addUrl = String.Format("~/App/SysManage/Module/Org/PartyOrgBranchEdit?id={0}&BranchID=" + BranchID, hdParentBranchID.Text);

        //    PageContext.RegisterStartupScript(Window1.GetShowReference(addUrl, "添加用户到当前部门"));
        //}

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindGrid();
        }
        #endregion

        #region 导入
        protected void fuFile_FileSelected(object sender, EventArgs e)
        {
            try
            {
                //1.获取从EXCEEL导入进来的数据
                DataSet ds = UploadFileHelp.ImportToDataSet(this.fuFile, "Sheet1");
                if (ds == null)
                {
                    return;
                }

                DateTime dtNow = DateTime.Now;
                string tempBranchID = string.Empty;
                StringBuilder sbsql = new StringBuilder();
                foreach (DataRow item in ds.Tables[0].Rows)
                {
                    tempBranchID = PartyOrg.QueryBranchID(Convert.ToString(item[0]));
                    if (tempBranchID == "")
                    {
                        Alert.Show("支部名称错误，请检查!");
                        return;
                    }
                    if (Convert.ToString(item[1]) == "" || Convert.ToString(item[2]) == "")
                    {
                        Alert.Show("摄像头名称和地址为必填，请检查!");
                        return;
                    }
                    sbsql.AppendFormat(@" INSERT INTO tblpartyvideoprobe(ID,BranchID,Address,Port,LinkMan,LinkPhone,CameraName,CameraLoginName,CameraLoginPwd,Description,CreateTime,CreateBy,ModifyBy,ModifyTime)
VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}'); ",
StringHelper.NewID, tempBranchID, Convert.ToString(item[2]), Convert.ToString(item[3]), Convert.ToString(item[6]), Convert.ToString(item[7]),
Convert.ToString(item[1]), Convert.ToString(item[4]), Convert.ToString(item[5]), Convert.ToString(item[8]), dtNow, CurrentUser.LoginID, CurrentUser.LoginID, dtNow);
                }
                if (MySqlHelper.ExecuteNonQuery(sbsql.ToString()) > 0)
                {
                    Alert.Show("数据导入成功!");
                }
                this.LoadData();

                MemoryCacheManager CacheManager = new MemoryCacheManager();
                CacheManager.Remove(CacheKeys.Cache_Branch_Camera_Tree_Navigation);
                CacheManager.Remove(CacheKeys.Cache_Camera_Branch_All);
            }
            catch (Exception ex)
            {

                Log4netHelper.WriteLog(ex);
                Alert.Show("导入文档格式不正确，请下载模板!");
                //Page.ClientScript.RegisterStartupScript(Page.GetType(), "", "alert('导入文档格式不正确，请下载模板！');", true);
                return;
            }
        }

        #endregion
    }
}